<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <style></style>
</head>

<body>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model="inputName" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model="inputAge" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男身男相">男身男相</option>
        <option value="男身女相">男身女相</option>
        <option value="女身女相">女身女相</option>
        <option value="女身男相">女身男相</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="item.id">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="e(index,item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
  <script src="../vue.js"></script>
  <script>
    const app = new Vue({
      el: "#app",
      //定义属性
      data: {
        gender: "男",
        inputName: "",
        inputAge: 0,
        selectId: "",
        list: [
          {
            id: 1,
            name: "小何想上天",
            age: 18,
            gender: "女身男相",
          },
          {
            id: 2,
            name: "老何头",
            age: 18,
            gender: "女身女相",
          },
          {
            id: 3,
            name: "大爱仙尊-何",
            age: 18,
            gender: "男身男相",
          },
        ],
      },
      //定义方法
      methods: {
        del(id) {
          this.list = this.list.filter((ele) => ele.id != id);
        },
        add() {
          // 1. 获取当前选中的元素
          const item = this.list.find((ele) => ele.id == this.selectId);
          // 2. 判断当前选中的元素是否已经存在
          if (item) {
            item.name = this.inputName;
            item.age = this.inputAge;
            item.gender = this.gender;
          } else {
            // 4. 如果不存在，就添加到list中
            this.list.push({
              id: this.list.length + 1,
              name: this.inputName,
              age: this.inputAge,
              gender: this.gender,
            });
            this.inputName = "";
            this.inputAge = 0;
            this.gender = "";
          }
        },
        e(index, id) {
          this.selectId = id;
          this.inputName = this.list[index].name;
          this.inputAge = this.list[index].age;
          this.gender = this.list[index].gender;
        },
      },
    });
  </script>
</body>

</html>